#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSettings>
#include <QUuid>
#include <QThread>
#include <QApplication>
#include <QCommonStyle>
#include <QClipboard>
#include <QInputDialog>
MainWindow::~MainWindow()
{
    delete ui;
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_passive_netWorkHandler(Q_NULLPTR),
    qtyInfo(new DeviceInfo(this)),
    m_changeDialog(new DialogChangePass(this,"更改密码")),
    m_isConnectedToNetty(false),
    m_trayMenu(new QMenu),
    m_trayIcon(new QSystemTrayIcon(this)),
    dlg_about_me(new  DialogTemplate(this))
{
    ui->setupUi(this);
    //--------------------按钮信号 到 主界面处理-------------------------------------------------
    connect(ui->bt_eye,&BtnShowPasswd::showPasswd,this,&MainWindow::showPasswd) ;
    //铅笔
    connect(ui->bt_changePasswd,&BtnChangePass::reflashPasswd,this,&MainWindow::getRandomString) ;
    connect(ui->bt_changePasswd,&BtnChangePass::setNewPasswd,this,&MainWindow::showChangePassDialog) ;
    connect(ui->bt_changePasswd,&BtnChangePass::copyPasswd,this,&MainWindow::copyPasswd) ;

    connect(ui->bt_settings,&BtnSettings::aboutQtyDesk,this,&MainWindow::aboutMe) ;
    connect(ui->bt_settings,&BtnSettings::aboutQtyDesk,this,&MainWindow::aboutMe) ;
    //--------------------按钮信号 到 主界面处理-------------------------------------------------
    //对话框信号 到 主界面处理
    connect(m_changeDialog,&DialogChangePass::setPasswdOk,this,&MainWindow::setTempPassword) ;


    QCommonStyle style;
    m_trayMenu->addAction(QIcon(style.standardPixmap(QStyle::SP_ComputerIcon)),"打开主界面");
    //m_trayMenu->addAction(QIcon(style.standardPixmap(QStyle::SP_MessageBoxInformation)),"基本设置");
    m_trayMenu->addAction(QIcon(style.standardPixmap(QStyle::SP_DialogCancelButton)),"退出");
    //托盘加入菜单
    m_trayIcon->setContextMenu(m_trayMenu);
    m_trayIcon->setIcon(QIcon(":/image/images/favicon.ico"));
    m_trayIcon->setToolTip("QtyDesk");

    //让托盘图标显示在系统托盘上
    m_trayIcon->show();
    //菜单子项触发
    connect(m_trayMenu,SIGNAL(triggered(QAction*)),this,SLOT(actionTriggered(QAction*)));
    //图标触发
    connect(m_trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    //加载配置文件
    loadSettings();

}
void MainWindow::aboutMe(){
    dlg_about_me->show();
}
//点击图标触发
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason ireason)
{
    switch (ireason)
    {
    case QSystemTrayIcon::Trigger:
        this->showNormal();
        break;
    case QSystemTrayIcon::DoubleClick:
        this->showNormal();
        break;
    case QSystemTrayIcon::MiddleClick:
        break;
    default:
        break;
    }
}
//菜单子项触发
void MainWindow::actionTriggered(QAction *action)
{
    if(action->text() == "打开主界面")
    {
        this->showNormal();
    }
    else if(action->text() == "退出"){
        emit closeSignal();
    }
}
//--------------------显示改变密码对话框------------------------------//
void MainWindow::showChangePassDialog(){
    m_changeDialog->exec();
}
//--------------------显示改变密码对话框------------------------------//

//加载配置文件
void MainWindow::loadSettings()
{
    QSettings settings("config.ini",QSettings::IniFormat);
    settings.beginGroup("REMOTE_DESKTOP_SERVER");

    QString remoteHost = settings.value("remoteHost").toString();
    if(remoteHost.isEmpty())
    {
        remoteHost = "qtydesk.com";
        settings.setValue("remoteHost",remoteHost);
    }
    int remotePort = settings.value("remotePort",0).toInt();
    if(remotePort == 0)
    {
        remotePort = 443;
        settings.setValue("remotePort",remotePort);
    }
    QString tempPass = settings.value("tempPass").toString();

    if(tempPass.isEmpty())
    {
        //得到随机数
        tempPass = getRandomString();
        //-----------------------加密------------------------------
        QByteArray jiami = tempPass.toLatin1() ;
        qtyInfo->xorData(jiami);
        QString fileTempPass = jiami;
        //-----------------------加密------------------------------
        settings.setValue("tempPass",fileTempPass);
    }else{
        //-----------------------解密------------------------------
        QByteArray jiemiPass = tempPass.toLatin1() ;
        qtyInfo->xorData(jiemiPass);
        tempPass = jiemiPass;
        //-----------------------解密------------------------------
    }

    qtyInfo->setRemoteInfo(remoteHost,static_cast<quint16>(remotePort));
    qtyInfo->setPassword(tempPass);

    settings.endGroup();
    settings.sync();
    //被控连接
    startPassiveConnect(qtyInfo);

}

//----------------------------设置临时密码--【start】---------------------------------------//
void MainWindow::setTempPassword(const QString &password){
    QSettings settings("config.ini",QSettings::IniFormat);
    settings.beginGroup("REMOTE_DESKTOP_SERVER");

    qtyInfo->setPassword(password);
    QByteArray newpass = password.toLatin1() ;
    qtyInfo->xorData(newpass);
    QString newpassstr = newpass;
    settings.setValue("tempPass",newpassstr);

    settings.endGroup();
    settings.sync();
}
//----------------------------设置临时密码--【end】----------------------------------------//

//-------------------------------得到随机密码--【start】-----------------------------------//
QString MainWindow::getRandomString()
{
    QString strUUID = QUuid::createUuid().toString().remove("{").remove("}").remove("-");
    QString randomPass = strUUID.right(6) ;
    setTempPassword(randomPass);
    return randomPass;
}
//-------------------------------得到随机密码--【end】--------------------------------------//

//--------------------------------开始被控连接处理--【start】---------------------------------//
void MainWindow::startPassiveConnect(DeviceInfo *ntInfo){
    QThread *thread = new QThread;
    m_passive_netWorkHandler = new PassiveHandler ;
    m_passive_netWorkHandler->initInfo(ntInfo,NetWorkHandler::PASSIVE);

    //线程开始,网络处理类创建socket
    connect(thread, &QThread::started, m_passive_netWorkHandler, &PassiveHandler::createSocket);
    //纽带关闭,网络类关闭socket
    connect(this, &MainWindow::closeSignal, m_passive_netWorkHandler, &PassiveHandler::removeSocket);
    //transfer结束了，其他关联也结束
    connect(m_passive_netWorkHandler, &PassiveHandler::finished, this, &MainWindow::finishedSockeHandler);
    connect(m_passive_netWorkHandler, &PassiveHandler::finished, thread, &QThread::quit);
    //线程结束,网络类销毁
    connect(thread, &QThread::finished, m_passive_netWorkHandler, &PassiveHandler::deleteLater);
    //线程结束,线程实例销毁
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
    //已连接状态
    connect(m_passive_netWorkHandler, &PassiveHandler::tfShowDeviceId,this, &MainWindow::showDeviceId);
    connect(m_passive_netWorkHandler, &PassiveHandler::connectedStatus,this, &MainWindow::showInfoMessage);
    //开始连接
    m_passive_netWorkHandler->moveToThread(thread);
    //开始线程，触发createSocket
    thread->start();
}
//--------------------------------开始被控连接处理--【end】----------------------------//


//---------------------------完成SOCKET 处理----------------------------------------//
void MainWindow::finishedSockeHandler()
{
    m_passive_netWorkHandler = Q_NULLPTR;
    if(!m_passive_netWorkHandler )
        QApplication::quit();
}
//---------------------------完成SOCKET 处理----------------------------------------//

/***************************连接远程设备【start】*************************************/
void MainWindow::on_bt_connectRemoteDevice_clicked()
{
    QString needRemoteID = ui->ed_remoteId->text().remove(QRegExp("\\s")) ;
    if(needRemoteID ==  ui->lb_showDeviceId->text().remove(QRegExp("\\s"))){
        dlg_err.setErrorTips("不能连接自己");
        dlg_err.exec();
        return ;
    }
    qtyInfo->setRemoteDeviceID(needRemoteID);
    new ScreenLook(qtyInfo);
    //slook->setGeometry(100,100,1000,800);
}
/***************************连接远程设备【end】****************************************/

/*---------------------------------显示设备ID----------------------------------------*/
void MainWindow::showDeviceId(QString id){
    id = id.mid(0,3)+" "+ id.mid(3,3) +" "+ id.mid(6,3) ;
    ui->lb_showDeviceId->setText(id);
    ui->bt_connectRemoteDevice->setEnabled(true);
}
/*---------------------------------显示设备ID----------------------------------------*/

//-------------------------------显示连接成功信息-------------------------------------//
void MainWindow::showInfoMessage(bool state)
{
    m_isConnectedToNetty = state;
    QString message("");

    if(m_isConnectedToNetty){
        ui->bt_lamp->setStyleSheet("background-color:rgb(50,190,166);border-radius:10px;");
        message.append("就绪");
    }else{
        ui->bt_lamp->setStyleSheet("background-color:rgb(185,54,54);border-radius:10px;");
        message.append("连接失败，启动重连。。。 ");
    }

    ui->lb_connect_state->setText(message);
}
//------------------------------显示连接成功信息---------------------------------------//

//---------------------------------显示密码-------------------------------------------//
void MainWindow::showPasswd(bool show)
{
    if(show){
        ui->lb_passwd->setText(qtyInfo->getTempPass());
    }else{
        ui->lb_passwd->setText("******");
    }
}
//---------------------------------显示密码------------------------------------------//

//---------------------------------复制信息-----------------------------------------//
void MainWindow::copyPasswd()
{
    QClipboard *board = QApplication::clipboard();
    board->setText(ui->lb_showDeviceId->text());
}
//---------------------------------复制信息-----------------------------------------//

//--------------------------------------------------------------------------------//
//-----------------------------ID 自动空格-----------------------------------------//
void MainWindow::on_ed_remoteId_textChanged(const QString &arg1)
{
    QString willRemoteId =ui->ed_remoteId->text();
    if(arg1.size() >= last_String.size()){
        if( arg1.length()%4 == 3 ){
            willRemoteId = willRemoteId+" ";
            ui->ed_remoteId->setText(willRemoteId);
        }
    }
    last_String = willRemoteId ;
}
//-----------------------------ID 自动空格-----------------------------------------//


